//
//  ChatMessageCell.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/30.
//  Copyright © 2019 Hins. All rights reserved.
//

import UIKit

class ChatMessageCell: UITableViewCell {

    lazy var coverLayer: CAShapeLayer = {
        let cover = CAShapeLayer()
        cover.fillColor = UIColor(white: 0.4, alpha: 0.3).cgColor
        return cover
    }()
    
    lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.textAlignment = .left
        return label
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let frame = CGRect(x: 0, y: 2, width: contentView.width, height: contentView.height - 4)
        coverLayer.frame = frame
        coverLayer.path = UIBezierPath(roundedRect: frame, cornerRadius: min(frame.height / 2, 5)).cgPath
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        messageLabel.attributedText = nil
    }
    
    private func setupUI() {
        backgroundColor = .clear
        contentView.backgroundColor = .clear
        contentView.layer.addSublayer(coverLayer)
        contentView.addSubview(messageLabel)
        messageLabel.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(8)
        }
    }
    
    func setMessage(message: RoomChatMessage, isMyself: Bool, isMaster: Bool) {
        var name: NSAttributedString
        if isMyself {
            name = NSAttributedString(string:  "我：", attributes: [.foregroundColor: UIColor.green, .font: UIFont.systemFont(ofSize: 15, weight: .medium)])
        } else if isMaster {
            name = NSAttributedString(string:  "(主播)" + message.name + "：", attributes: [.foregroundColor: UIColor.standardColor, .font: UIFont.systemFont(ofSize: 15, weight: .medium)])
        } else {
            name = NSAttributedString(string: message.name + "：", attributes: [.foregroundColor: UIColor.white, .font: UIFont.systemFont(ofSize: 15, weight: .medium)])
        }
        let content = NSAttributedString(string: message.content,
                                         attributes: [.foregroundColor: UIColor.yellow, .font: UIFont.systemFont(ofSize: 15)])
        let message = NSMutableAttributedString()
        message.append(name)
        message.append(content)
        messageLabel.attributedText = message
    }
}

